package com.itheima.question.timer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.admin.pojo.Question;
import com.itheima.admin.vo.QuestionVo;
import com.itheima.common.contants.RedisPicConstants;
import com.itheima.common.safe.PicSafe;
import com.itheima.common.safe.TextSafe;
import com.itheima.question.mapper.QuestionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Set;


@Component
@Slf4j
public class AddQuestionTask {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QuestionMapper questionMapper;

    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Scheduled(cron = "0/10 * * * * ?")
    public void AddQuestion(){
        Set<String> queIds = redisTemplate.opsForSet().members("que_id");

        if(queIds != null){
            log.info("定时任务开始执行，需要审核的题目有："+queIds);
            for(String id : queIds) {
                try {
                    Question que = questionMapper.selectById(id);
                    if(TextSafe.QuestionSafe(que.getSubject()).equals("pass") ){
                        String pid = que.getPicture();
                        redisTemplate.opsForSet().add(RedisPicConstants.USE_PIC,pid.replace(fileServerUrl,""));
                        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
                        queryWrapper.like("id",id);
                        que.setReviewStatus("1");
                        int i = questionMapper.update(que,queryWrapper);
                        if(i>0){
                            redisTemplate.opsForSet().remove("que_id",id);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
